package com.kwlt.smc.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kwlt.smc.entity.InterRespInfo;
import com.kwlt.smc.entity.SmsInfo;
import com.kwlt.smc.entity.SmsInfoFocshcn;
import com.kwlt.smc.entity.User;
import com.kwlt.smc.service.BlacklistService;
import com.kwlt.smc.service.ISendSms;
import com.kwlt.smc.service.IValidationSms;
import com.kwlt.smc.service.KeywordService;
import com.kwlt.smc.util.ConUtils;
import com.kwlt.smc.util.Constants;
import com.kwlt.smc.util.SendHttpUtils;


@Controller
@RequestMapping(value="/sms")
public class SendSmsController {
	public static Logger logger =  LoggerFactory.getLogger(SendSmsController.class);
	@Autowired
	private IValidationSms iValidationSms;
	@Autowired
	private ISendSms iSendSms;
	@Autowired
	private BlacklistService blacklistService;
	@Autowired
	private KeywordService keywordService;
	/**
	 * 
	 * @param user 用户名
	 * @param pwd 密码
	 * @param dest 下行目的手机号,支持批量发送，多个手机号之间用英文半角逗号(,)分隔
	 * @param msg 下行短信内容，有非英文字符需要进行URLEncode指定字符集UTF-8
	 * @param ext 扩展号码
	 * @param cc 通道编号
	 * @param msgtype 消息类型0：默认是普通短信；1：二进制；2：wap push
	 * @param authcode dest+msg+md5密钥]用md5数字签名并转为16进制格式（长度为32字节），如果双方约定不使用MD5密钥可以不使用这个字段。
	 * @param ip 用户IP
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="send")//, method = RequestMethod.POST
	public void sendSms(SmsInfo smsInfo,HttpServletRequest request, HttpServletResponse response) throws IOException{
		InterRespInfo resp = new InterRespInfo();
		smsInfo.setIp(request.getRemoteAddr());
		String sendtime = smsInfo.getSendtime();
		iValidationSms.validationSms(smsInfo,resp);
		PrintWriter out = response.getWriter();
		if("0".equals(resp.getRespCode())){
			//如果验证成功
			try{
				//再次过滤黑名单和
				if(keywordService.validationKeyword(smsInfo,"1",null,null) && keywordService.validationKeyword(smsInfo,"4",null,null) ){
					if(blacklistService.validationBlack(smsInfo)){
						User user = smsInfo.getOuser();
						//判断用户是否传送MSGID，1：代表未传送用户MIGID、0：代表用户传送MSGID
						String localMsgId = ConUtils.getMsgId(user.getUserNumbers(),smsInfo.getMsgid()==null?"1":"0");
						if(sendtime!=null && !"".equals(sendtime)){
							Map<String, String> sendMap = getSendMap(smsInfo,localMsgId);
							String string = SendHttpUtils.sendHttpPostRequest(Constants.TIMMING_URL, sendMap, "UTF-8");
							if("999".equals(string)){
								resp.setRespCode(string);
								resp.setRespDesc("sysexp");
							}else{
								resp.setMsgId(string);
							}
						}else{
							iSendSms.sendSmsToStorage(smsInfo,resp,localMsgId);
						}
					}else{
						resp.setRespCode("007");
						resp.setRespDesc("黑名单错误");
					}
				}else{
					resp.setRespCode("101");
					resp.setRespDesc("短信内容错误（为空或者有过滤关键字）");
				}
			}catch(Exception e){
				e.printStackTrace();
				resp.setRespCode("999");
				resp.setRespDesc("sysexp");
			}
		}
		out.print(resp.getRespCode()+(StringUtils.isBlank(resp.getMsgId())?"":":"+resp.getMsgId()));
		String log = getLog(resp, smsInfo);
		logger.info(log);
	}
	
	private String getLog(InterRespInfo resp,SmsInfo smsInfo){
		StringBuffer logInfo = new StringBuffer();
		logInfo.append(smsInfo.getUser()).append("\t");
		logInfo.append(resp.getRespCode()).append("\t");
		logInfo.append(resp.getRespDesc()).append("\t");
		logInfo.append(resp.getMsgId()).append("\t");
		logInfo.append(smsInfo.getExt()).append("\t");
		logInfo.append(smsInfo.getSendtime()).append("\t");
		Set mobileSet = smsInfo.getMobileChannelSet();
		String mobileNumbers = getChannelNumbers(mobileSet);
		if(mobileNumbers!=null && mobileNumbers.length()>0){
			mobileNumbers = mobileNumbers.substring(0, mobileNumbers.length()-1);
			logInfo.append(mobileNumbers).append(",");
		}
		Set unicomSet = smsInfo.getUnicomChannelSet();
		String unicomNumbers = getChannelNumbers(unicomSet);
		if(unicomNumbers!=null && unicomNumbers.length()>0){
			unicomNumbers = unicomNumbers.substring(0, unicomNumbers.length()-1);
			logInfo.append(unicomNumbers).append(",");
		}
		Set telecomSet = smsInfo.getTelecomChannelSet();
		String telecomNumbers = getChannelNumbers(telecomSet);
		if(telecomNumbers!=null && telecomNumbers.length()>0){
			telecomNumbers = telecomNumbers.substring(0, telecomNumbers.length()-1);
			logInfo.append(telecomNumbers);
		}
		logInfo.append("\t");
		logInfo.append(smsInfo.getMsg().replaceAll("\n", "")+"\t");
		logInfo.append(smsInfo.getDest());
		
		return logInfo.toString();
	}
	
	public Map<String,String> getSendMap(SmsInfo smsInfo,String localMsgId){
		Map<String,String> map = new HashMap<String,String>();
		map.put("user", smsInfo.getUser());
		map.put("dest", smsInfo.getDest());
		map.put("msg", smsInfo.getMsg());
		map.put("sendtime", smsInfo.getSendtime());
		map.put("msgId", localMsgId);
		return map;
	}
	
	private String getChannelNumbers(Set<String> set){
		StringBuffer sb = new StringBuffer();
		for(String code:set){
			sb.append(code).append(",");
		}
		return sb.toString();
	}
}
